/*
 * @Author: hujingyang
 * @Date: 2021-09-15 17:16:00
 * @Description: 404页面制造雪景
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-12-02 15:36:20
 * @FilePath: \ks-cjhd-web\src\common\makeSnow.js
 * @IDE: Created by VScode.
 */

/**404页面制造雪景 */
export function makeSnow(canvas) {
  var ctx = canvas.getContext("2d");
  var width = 0;
  var height = 0;
  var particles = [];

  var Particle = function () {
    this.x = this.y = this.dx = this.dy = 0;
    this.reset();
  };

  Particle.prototype.reset = function () {
    this.y = Math.random() * height;
    this.x = Math.random() * width;
    this.dx = Math.random() * 1 - 0.5;
    this.dy = Math.random() * 0.5 + 0.5;
  };

  function createParticles(count) {
    if (count != particles.length) {
      particles = [];
      for (var i = 0; i < count; i++) {
        particles.push(new Particle());
      }
    }
  }

  function onResize() {
    width = window.innerWidth;
    height = window.innerHeight;
    canvas.width = width;
    canvas.height = height;

    createParticles((width * height) / 10000);
  }

  function updateParticles() {
    ctx.clearRect(0, 0, width, height);
    ctx.fillStyle = "#f6f9fa";

    particles.forEach(function (particle) {
      particle.y += particle.dy;
      particle.x += particle.dx;

      if (particle.y > height) {
        particle.y = 0;
      }

      if (particle.x > width) {
        particle.reset();
        particle.y = 0;
      }

      ctx.beginPath();
      ctx.arc(particle.x, particle.y, 5, 0, Math.PI * 2, false);
      ctx.fill();
    });

    window.requestAnimationFrame(updateParticles);
  }

  onResize();
  updateParticles();
}
